import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiFunction;

/**
 * 每一行代码，都是改变世界的力量
 *
 * @author 郭帅
 * @date 2022/11/11 14:49
 */
public class CompletableCallbackTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Void> runFuture = CompletableFuture.runAsync(() -> System.out.println("i am task"))
                .thenRun(() -> System.out.println("i am sub task"))
                .thenRunAsync(() -> System.out.println("i am sub sub task"))
                .thenAccept(System.out::println);


        CompletableFuture<Void> exceptionFuture = CompletableFuture.runAsync(() -> {
            int a = 1 / 0;
            System.out.println(a);
        }).exceptionally(throwable -> {
            System.out.println(throwable.getMessage());
            return null;
        }).handle(new BiFunction<Void, Throwable, Void>() {
            @Override
            public Void apply(Void unused, Throwable throwable) {
                return null;
            }
        });

        CompletableFuture<Void> whenCompleteFuture = CompletableFuture.runAsync(() -> {
            int a = 1 / 0;
            System.out.println(a);
        }).whenComplete((unused, throwable) -> System.out.println("i am finished"));


        CompletableFuture<Void> handleFuture = CompletableFuture.runAsync(() -> {
            int a = 1 / 0;
            System.out.println(a);
        }).handle((unused, throwable) -> {

            System.out.println(unused);
            System.out.println(throwable.getMessage());
            return null;
        });
        System.out.println(handleFuture.get());

        whenCompleteFuture.get();

        CompletableFuture<String> supplyFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("this is supplyAsync");
            return "ok";
        });
        runFuture.get();
//        String result = supplyFuture.get();
//        System.out.println(result);


    }
}
